<template>
  <view class="page">
    <view class="payment-card">
      <view class="icon-section">
        <text class="payment-icon">💳</text>
      </view>
      
      <view class="amount-section">
        <text class="amount-label">支付金额</text>
        <view class="amount-value">
          <text class="amount-symbol">¥</text>
          <text class="amount-number">{{ amount }}</text>
        </view>
      </view>
      
      <view class="order-info">
        <text class="info-label">订单号：</text>
        <text class="info-value">{{ orderNo }}</text>
      </view>
      
      <view class="payment-methods">
        <view class="method-title">支付方式</view>
        <view 
          class="method-item active"
        >
          <text class="method-icon">💚</text>
          <text class="method-name">微信支付</text>
          <text class="method-check">✓</text>
        </view>
      </view>
      
      <view class="btn-pay" @click="doPay">
        <text class="btn-text">确认支付</text>
      </view>
      
      <view class="btn-cancel" @click="cancelPay">
        <text class="cancel-text">取消支付</text>
      </view>
    </view>
    
    <view class="tips">
      <text class="tips-title">💡 温馨提示</text>
      <text class="tips-text">• 点击"确认支付"将调起微信支付</text>
      <text class="tips-text">• 支付完成后，订单将自动进入"待接单"状态</text>
      <text class="tips-text">• 如支付过程中遇到问题，可在订单列表重新支付</text>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      orderNo: '',
      amount: '',
      paying: false
    }
  },
  onLoad(options) {
    this.orderId = options.orderId || ''
    this.orderNo = options.orderNo || ''
    this.amount = options.amount || '0.00'
  },
  methods: {
    async doPay() {
      if (this.paying) return
      
      // 直接调用微信支付
      await this.doWxPay()
    },
    
    // 微信支付
    async doWxPay() {
      this.paying = true
      uni.showLoading({ title: '正在调起支付...' })
      
      try {
        // 1. 获取用户openid（从登录信息中获取或通过wx.login获取）
        const openid = await this.getUserOpenId()
        
        if (!openid) {
          throw new Error('获取用户openid失败，请重新登录')
        }
        
        // 2. 创建微信支付订单
        const { createWxPayOrder } = require('@/api/payment')
        const payData = await createWxPayOrder({
          orderId: this.orderId,
          openid: openid
        })
        
        uni.hideLoading()
        
        // 3. 调起微信支付
        const payResult = await uni.requestPayment({
          provider: 'wxpay',
          timeStamp: payData.timeStamp,
          nonceStr: payData.nonceStr,
          package: payData.packageValue,
          signType: payData.signType,
          paySign: payData.paySign
        })
        
        // 4. 支付成功，查询订单状态
        await this.checkPaymentStatus()
        
      } catch (error) {
        console.error('微信支付失败:', error)
        uni.hideLoading()
        
        // 用户取消支付
        if (error.errMsg && error.errMsg.includes('cancel')) {
          uni.showToast({
            title: '已取消支付',
            icon: 'none'
          })
        } else {
          uni.showModal({
            title: '支付失败',
            content: error.message || '支付过程中出现问题，请重试',
            showCancel: false
          })
        }
      } finally {
        this.paying = false
      }
    },
    
    // 获取用户openid
    async getUserOpenId() {
      try {
        // 方式1：从store中获取（如果已存在）
        const openid = this.$store.getters['user/openid']
        if (openid) {
          //console.log('从store获取openid:', openid)
          return openid
        }
        
        // 方式2：调用wx.login获取code，然后向后端换取openid
        //console.log('开始调用wx.login获取code...')
        const loginRes = await uni.login({
          provider: 'weixin'
        })
        
        if (loginRes[1] && loginRes[1].code) {
          const code = loginRes[1].code
          //console.log('获取code成功:', code)
          
          // 调用后端接口，用code换取openid
          const { getWxOpenid } = require('@/api/user')
          const result = await getWxOpenid(code)
          
          if (result && result.openid) {
            //console.log('获取openid成功:', result.openid)
            
            // 保存到store
            this.$store.commit('user/SET_OPENID', result.openid)
            
            return result.openid
          } else {
            throw new Error('后端返回的openid为空')
          }
        } else {
          throw new Error('获取微信登录code失败')
        }
        
      } catch (error) {
        console.error('获取openid失败:', error)
        throw error
      }
    },
    
    // 查询支付状态
    async checkPaymentStatus() {
      try {
        uni.showLoading({ title: '确认支付结果...' })
        
        const { queryPayStatus } = require('@/api/payment')
        const result = await queryPayStatus(this.orderId)
        
        uni.hideLoading()
        
        if (result.paid) {
          // 支付成功
          uni.showToast({
            title: '支付成功',
            icon: 'success',
            duration: 2000
          })
          
          // 跳转到订单详情
          setTimeout(() => {
            uni.redirectTo({
              url: `/pages/order/detail?id=${this.orderId}`
            })
          }, 2000)
        } else {
          // 支付未完成
          uni.showModal({
            title: '支付未完成',
            content: '支付结果确认中，请稍后在订单列表查看',
            showCancel: false,
            success: () => {
              uni.redirectTo({
                url: '/pages/order/index'
              })
            }
          })
        }
      } catch (error) {
        console.error('查询支付状态失败:', error)
        uni.hideLoading()
        
        uni.showModal({
          title: '提示',
          content: '支付结果确认中，请稍后在订单列表查看',
          showCancel: false,
          success: () => {
            uni.redirectTo({
              url: '/pages/order/index'
            })
          }
        })
      }
    },
    
    cancelPay() {
      uni.showModal({
        title: '提示',
        content: '确定要取消支付吗？订单将保留，您可以稍后在订单列表中继续支付',
        success: (res) => {
          if (res.confirm) {
            uni.redirectTo({
              url: '/pages/order/index'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.payment-card {
  background: #fff;
  border-radius: 24rpx;
  padding: 48rpx 32rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1);
  margin-bottom: 40rpx;
}

.icon-section {
  text-align: center;
  margin-bottom: 32rpx;
  
  .payment-icon {
    font-size: 120rpx;
  }
}

.amount-section {
  text-align: center;
  margin-bottom: 40rpx;
  
  .amount-label {
    font-size: 26rpx;
    color: #999;
    display: block;
    margin-bottom: 16rpx;
  }
  
  .amount-value {
    display: flex;
    align-items: baseline;
    justify-content: center;
    gap: 8rpx;
    
    .amount-symbol {
      font-size: 36rpx;
      color: #ff4d4f;
      font-weight: bold;
    }
    
    .amount-number {
      font-size: 64rpx;
      color: #ff4d4f;
      font-weight: bold;
    }
  }
}

.order-info {
  text-align: center;
  padding: 24rpx 0;
  border-top: 1rpx solid #f0f0f0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 32rpx;
  
  .info-label {
    font-size: 24rpx;
    color: #999;
  }
  
  .info-value {
    font-size: 24rpx;
    color: #666;
    margin-left: 8rpx;
  }
}

.payment-methods {
  margin-bottom: 40rpx;
  
  .method-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
  }
}

.method-item {
  display: flex;
  align-items: center;
  padding: 28rpx 24rpx;
  background: #f5f7fa;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
  position: relative;
  
  &.active {
    background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
    border: 2rpx solid #667eea;
  }
  
  .method-icon {
    font-size: 40rpx;
    margin-right: 20rpx;
  }
  
  .method-name {
    flex: 1;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
  }
  
  .method-desc {
    font-size: 22rpx;
    color: #999;
    margin-left: 12rpx;
  }
  
  .method-check {
    font-size: 32rpx;
    color: #667eea;
    font-weight: bold;
  }
}

.btn-pay {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  height: 88rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 24rpx;
  
  .btn-text {
    font-size: 32rpx;
    color: #fff;
    font-weight: bold;
  }
}

.btn-cancel {
  text-align: center;
  
  .cancel-text {
    font-size: 28rpx;
    color: #999;
  }
}

.tips {
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16rpx;
  padding: 32rpx;
  
  .tips-title {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    display: block;
    margin-bottom: 20rpx;
  }
  
  .tips-text {
    font-size: 24rpx;
    color: #666;
    line-height: 2;
    display: block;
  }
}
</style>

